package cn.glow.readingcloud.account.service.impl;


import cn.glow.readingcloud.account.dao.UserMapper;
import cn.glow.readingcloud.account.dto.AuthDto;
import cn.glow.readingcloud.account.pojo.UserRegister;
import cn.glow.readingcloud.account.pojo.UserView;
import cn.glow.readingcloud.account.service.UserService;
import cn.glow.readingcloud.account.util.JwtUtil;
import cn.glow.readingcloud.common.pojo.User;
import cn.glow.readingcloud.common.result.Result;
import cn.glow.readingcloud.common.result.ResultUtil;
import cn.glow.readingcloud.common.utils.CommonUtil;
import cn.glow.readingcloud.common.utils.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import static cn.glow.readingcloud.common.constant.JwtConstant.EXPIRE_DAY;

import java.util.Calendar;
import java.util.Date;

/**
 * @Author Glow
 * @Date 2023-04-10 15:21:22
 * @Description
 * @Version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public User selectByLoginName(String loginName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getLoginName,loginName);
       return userMapper.selectOne(queryWrapper);

    }

    @Override
    public Result register(UserRegister userRegister) {
        User userDb = this.selectByLoginName(userRegister.getLoginName());
        if (userDb != null)
        {
            return ResultUtil.verificationFailed().buildMessage(userRegister.getLoginName()+"已经被注册，请重试");
        }
        User user = new User();
        //将原用户的密码复制
        BeanUtils.copyProperties(userRegister,user);
        //对用户输入的密码进行MD5加密
        String encryptPwd = UserUtil.getUserEncryptPassword(userRegister.getLoginName(),user.getUserPwd());
        user.setUserPwd(encryptPwd);
        try {
            //设置默认投降
            user.setHeadImgUrl("https://img1.baidu.com/it/u=2472816488,4047356479&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400");
            user.setUuid(CommonUtil.getUUID());
            userMapper.insert(user);
        }catch (Exception e)
        {
            LOGGER.error("注册失败,原因如下:{},用户信息user:：{}",e,user);
            return ResultUtil.fail().buildMessage("注册失败！");

        }
        return  ResultUtil.success().buildMessage("注册成功！");
    }

    @Override
    public Result<AuthDto> login(String loginName, String password) {
        try{
            User userCheck = this.selectByLoginName(loginName);
            if(userCheck == null)
            {
                return ResultUtil.notFound().buildMessage("不存在该用户或密码错误！请重试！");
            }
            //校验密码
            String encrypwd = UserUtil.getUserEncryptPassword(loginName,password);
            if(!userCheck.getUserPwd().equals(encrypwd))
            {
                return ResultUtil.verificationFailed().buildMessage("密码错误，请重试！");
            }
            //校验成功，返回用户信息
            AuthDto authDto = new AuthDto();
            UserView userView = new UserView();
            BeanUtils.copyProperties(userCheck,userView);
            authDto.setUser(userView);
            String token = JwtUtil.buildJwt(this.getLoginExpre(),userView);
            authDto.setToken(token);
            //将登录信息保存在Redis中
            redisTemplate.opsForHash().put("user",token,userView);
            return ResultUtil.success(authDto);
        }catch (Exception e)
        {
            LOGGER.error("登录失败了！{}; loginName:{}", e, loginName);
            return ResultUtil.fail().buildMessage("登录失败，服务器被吃了＝(#>д<)ﾉ ！请重试。 ");
        }

    }

    /**
     * 获取登陆过期时间
     * @return
     */
    private Date getLoginExpre(){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, EXPIRE_DAY);
        return calendar.getTime();
    }
    @Override
    public Result logout(String token) {
        UserView  userRedis = (UserView) redisTemplate.opsForHash().get("user",token);
        if(userRedis == null)
        {
            return ResultUtil.error("该用户未登录，请重新登录！");
        }
        redisTemplate.opsForHash().delete("user",token);
        return ResultUtil.success("已成功注销");
    }

    @Override
    public Result update(AuthDto authDto) {
        try {
            User user = new User();
            BeanUtils.copyProperties(authDto.getUser(),user);
            userMapper.updateById(user);
            redisTemplate.opsForHash().put("user",authDto.getToken(),authDto.getUser());
            return  ResultUtil.success("更新用户信息完成！");
        }catch (Exception e)
        {
            return ResultUtil.error("更新失败，寄了！");
        }


    }


}
